package com.daoos.swagger;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

@Component
@Log4j2
public class ScanSnippet {
	private Logger log = LogManager.getLogger(ScanSnippet.class);

	/**
	 * 查询所有的拥有@ApiOperation注解和@Snippet注解的方法，找到@Snippet注解中定义的snippetClass，放入缓存备用
	 *
	 * @param basePackages
	 *            扫描路径
	 * @return 扫描到的类
	 */
	private void doScan(String basePackages) throws Exception {
		ScanUtils.scanner(basePackages, classMetadata -> {
			Class beanClass = this.getClass().getClassLoader().loadClass(classMetadata.getClassName());
			for (Method method : beanClass.getMethods()) {
				ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
				Snippet snippet = method.getAnnotation(Snippet.class);
				if (apiOperation != null && snippet != null) {
					String apiName = apiOperation.value();
					Class snippetClass = snippet.snippetClass();
					if (ISnippet.class.isAssignableFrom(snippetClass)) {
						try {
							ISnippet _snippet = (ISnippet) snippetClass.newInstance();
							_snippet.setHttpMethod(snippet.httpMethod());
							_snippet.setMediaType(snippet.mediaType());
							_snippet.setURL(snippet.url());

							log.info("扫描到了：apiName={" + apiName + "},_snippet={" + _snippet + "}");
							snippetMap.put(apiName, _snippet);
						} catch (InstantiationException | IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
	}

	/**
	 * 启动时扫描
	 */
	@PostConstruct
	public void scanSnippetMethod() {
		try {
			this.doScan("test");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * snippetMap
	 */
	public final static Map<String, ISnippet> snippetMap = new HashMap<>();
}